import time

from selenium.webdriver.support import expected_conditions as ec
from selenium.webdriver.support.wait import WebDriverWait

from autoTest_ceshopAdmin.utils.log_util import logger


class Base():
    def __init__(self,driver):
        self.driver = driver

    # 查找单个元素
    def find_element(self,locator):
        try:
            logger.info(f'查找元素：{locator}')
            # print(f'查找元素：{locator}')
            return WebDriverWait(self.driver,5).until(ec.visibility_of_element_located(locator))
        except Exception as e:
            logger.info(f'元素{locator}定位失败。失败原因是:\n {e}')
            # print(f'元素{locator}定位失败。失败原因是:\n {e}')

    # 查找多个元素
    def find_elements(self,locator):
        try:
            return WebDriverWait(self.driver,5).until(ec.visibility_of_all_elements_located(locator))
        except Exception as e:
            logger.info(f'元素{locator}定位失败。失败原因是:\n {e}')
            # print(f'元素{locator}定位失败。失败原因是:\n {e}')

    # 输入数据
    def input_data(self,locator,keywords):
        # 查找元素
        element = self.find_element(locator)
        # 清空输入框的内容
        element.clear()
        # 输入内容
        logger.info((f'输入数据: {keywords}'))
        # print(f'输入数据: {keywords}')
        element.send_keys(keywords)

    # 点击
    def click_element(self,locator):
        # 查找元素
        element = self.find_element(locator)
        # 点击元素
        print(f'点击元素: {locator}')
        element.click()
        time.sleep(0.5)

    # 警告框切换
    def switchAlert(self,keywords=None,text=True,action=True):
        try:
            #  切换到警告框
            alert = self.driver.switch_to.alert

            # 输入信息
            if keywords:
                alert.send_keys(keywords = None)

            # 获取文本
            if text:
                text = alert.text

            # 点击确认
            if action:
                alert.accept()
            else:
                alert.dismiss()

            if text:
                print(f'返回文本信息{text}')
                return text
        except  Exception as e:
            print(f"警告框的操作失败，错误信息是：\n{e}")

    # 获取文本内容
    def getText(self,locator):
        element = self.find_element(locator)
        print(f'找到元素：{locator}')
        text = element.text
        return text

    # 切换指定表单
    def switchFrame(self,locator):
        frame = self.find_element(locator)
        self.driver.switch_to.frame(frame)



















